Namespace DotNetNuke.Modules.ActiveForums
    Partial Public Class af_modtopics_new
        Inherits ForumBase
#Region "Private Members"
        Private bModDelete As Boolean = False
        Private bModEdit As Boolean = False
        Private bModApprove As Boolean = False
        Private bModMove As Boolean = False
        Private bCanMod As Boolean = False

#End Region
#Region "Event Handlers"
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Request.IsAuthenticated AndAlso ForumUser.Profile.IsMod Then
                If ForumId > 0 Then
                    SetPermissions(ForumId)
                End If


                If Not cbMod.IsCallback Then
                    lblHeader.Text = Utilities.GetSharedResource("[RESX:PendingPosts]")
                    BuildModList()
                End If

            Else
                Response.Redirect(NavigateUrl(ForumTabId))
            End If

        End Sub
        Private Sub cbMod_Callback(ByVal sender As Object, ByVal e As Modules.ActiveForums.Controls.CallBackEventArgs) Handles cbMod.Callback
            Dim ms As SettingsInfo = DataCache.MainSettings(ForumModuleId)
            Dim fi As Forum = Nothing
            If e.Parameters.Length > 0 Then
                If ForumId < 1 Then
                    SetPermissions(CInt(e.Parameters(1)))
                    Dim fc As New ForumController
                    fi = fc.Forums_Get(CInt(e.Parameters(1)), -1, False, True)
                Else
                    fi = ForumInfo
                End If
                Select Case e.Parameters(0).ToLowerInvariant
                    Case "moddel"
                        If bModDelete Then
                            Dim delAction As Integer = ms.DeleteBehavior
                            Dim tmpForumId As Integer = -1
                            Dim tmpTopicId As Integer = -1
                            Dim tmpReplyId As Integer = -1
                            tmpForumId = CInt(e.Parameters(1))
                            tmpTopicId = CInt(e.Parameters(2))
                            tmpReplyId = CInt(e.Parameters(3))
                            Dim auth As Author = Nothing
                            If fi.ModDeleteTemplateId > 0 Then
                                Try
                                    Dim oEmail As New Email
                                    oEmail.SendEmail(fi.ModDeleteTemplateId, PortalId, ForumModuleId, ForumTabId, tmpForumId, tmpTopicId, tmpReplyId, String.Empty, auth)
                                Catch ex As Exception

                                End Try

                            End If
                            If tmpForumId > 0 And tmpTopicId > 0 And tmpReplyId = 0 Then
                                Dim tc As New TopicsController
                                Dim ti As TopicInfo = tc.Topics_Get(PortalId, ForumModuleId, tmpTopicId)
                                If Not ti Is Nothing Then
                                    auth = ti.Author
                                End If
                                tc.Topics_Delete(PortalId, ModuleId, tmpForumId, tmpTopicId, delAction)
                            ElseIf tmpForumId > 0 And tmpTopicId > 0 And tmpReplyId > 0 Then
                                Dim rc As New ReplyController
                                Dim ri As ReplyInfo = rc.Reply_Get(PortalId, ForumModuleId, tmpTopicId, tmpReplyId)
                                If Not ri Is Nothing Then
                                    auth = ri.Author
                                End If
                                rc.Reply_Delete(PortalId, tmpForumId, tmpTopicId, tmpReplyId, delAction)
                            End If

                        End If
                    Case "modreject"
                        Dim tmpForumId As Integer = 0
                        Dim tmpTopicId As Integer = 0
                        Dim tmpReplyId As Integer = 0
                        Dim tmpAuthorId As Integer = 0
                        tmpForumId = CInt(e.Parameters(1))
                        tmpTopicId = CInt(e.Parameters(2))
                        tmpReplyId = CInt(e.Parameters(3))
                        tmpAuthorId = CInt(e.Parameters(4))
                        Dim mc As New ModController
                        mc.Mod_Reject(PortalId, ForumModuleId, UserId, tmpForumId, tmpTopicId, tmpReplyId)
                        If fi.ModRejectTemplateId > 0 And tmpAuthorId > 0 Then
                            Dim uc As New DotNetNuke.Entities.Users.UserController
                            Dim ui As DotNetNuke.Entities.Users.UserInfo = uc.GetUser(PortalId, tmpAuthorId)
                            If Not ui Is Nothing Then
                                Dim au As New Author
                                au.AuthorId = tmpAuthorId
                                au.DisplayName = ui.DisplayName
                                au.Email = ui.Email
                                au.FirstName = ui.FirstName
                                au.LastName = ui.LastName
                                au.Username = ui.Username
                                Dim oEmail As New Email
                                oEmail.SendEmail(fi.ModRejectTemplateId, PortalId, ForumModuleId, ForumTabId, tmpForumId, tmpTopicId, tmpReplyId, String.Empty, au)
                            End If

                        End If

                    Case "modappr"
                        Dim tmpForumId As Integer = -1
                        Dim tmpTopicId As Integer = -1
                        Dim tmpReplyId As Integer = -1
                        tmpForumId = CInt(e.Parameters(1))
                        tmpTopicId = CInt(e.Parameters(2))
                        tmpReplyId = CInt(e.Parameters(3))
                        Dim sSubject As String = String.Empty
                        Dim sBody As String = String.Empty
                        If tmpForumId > 0 And tmpTopicId > 0 And tmpReplyId = 0 Then
                            Dim tc As New TopicsController
                            Dim ti As TopicInfo = tc.Topics_Get(PortalId, ForumModuleId, tmpTopicId, tmpForumId, -1, False)
                            If Not ti Is Nothing Then
                                sSubject = ti.Content.Subject
                                sBody = ti.Content.Body
                                ti.IsApproved = True
                                tc.TopicSave(PortalId, ti)
                                tc.Topics_SaveToForum(tmpForumId, tmpTopicId, PortalId, ModuleId)
                                'TODO: Add Audit log for who approved topic
                                If fi.ModApproveTemplateId > 0 And ti.Author.AuthorId > 0 Then
                                    Dim oEmail As New Email
                                    oEmail.SendEmail(fi.ModApproveTemplateId, PortalId, ForumModuleId, ForumTabId, tmpForumId, tmpTopicId, tmpReplyId, String.Empty, ti.Author)
                                End If

                                Subscriptions.SendSubscriptions(PortalId, ForumModuleId, ForumTabId, tmpForumId, tmpTopicId, 0, ti.Content.AuthorId)

                                Try
                                    Dim ctlUtils As New ControlUtils
                                    Dim sUrl As String = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, fi.ForumGroup.PrefixURL, fi.PrefixURL, fi.ForumGroupId, fi.ForumID, TopicId, ti.TopicUrl, -1, -1, String.Empty, 1, fi.SocialGroupId) ' Utilities.NavigateUrl(ForumTabId, "", ParamKeys.ViewType & "=" & Views.Topic & "&" & ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId)
                                    If sUrl.Contains("~/") Or Not Request.QueryString("asg") Is Nothing Then
                                        sUrl = Utilities.NavigateUrl(ForumTabId, "", ParamKeys.TopicId & "=" & TopicId)
                                    End If
                                    Dim amas As New Social
                                    If Request.QueryString("asg") Is Nothing And Not String.IsNullOrEmpty(MainSettings.ActiveSocialTopicsKey) And fi.ActiveSocialEnabled Then
                                        amas.AddTopicToJournal(PortalId, ForumModuleId, ForumId, ti.TopicId, ti.Author.AuthorId, sUrl, sSubject, ti.Content.Summary, sBody, fi.ActiveSocialSecurityOption, fi.Security.Read, SocialGroupId)
                                    Else
                                        amas.AddForumItemToJournal(PortalId, ForumModuleId, ti.Author.AuthorId, "forumtopic", sUrl, sSubject, sBody)
                                    End If

                                Catch ex As Exception
                                    DotNetNuke.Services.Exceptions.LogException(ex)
                                End Try
                            End If
                        ElseIf tmpForumId > 0 And tmpTopicId > 0 And tmpReplyId > 0 Then
                            Dim rc As New ReplyController
                            Dim ri As ReplyInfo = rc.Reply_Get(PortalId, ForumModuleId, tmpTopicId, tmpReplyId)
                            If Not ri Is Nothing Then
                                ri.IsApproved = True
                                sSubject = ri.Content.Subject
                                sBody = ri.Content.Body
                                rc.Reply_Save(PortalId, ri)
                                Dim tc As New TopicsController
                                tc.Topics_SaveToForum(tmpForumId, tmpTopicId, PortalId, ModuleId, tmpReplyId)
                                Dim ti As TopicInfo = tc.Topics_Get(PortalId, ForumModuleId, tmpTopicId, tmpForumId, -1, False)
                                'TODO: Add Audit log for who approved topic
                                If fi.ModApproveTemplateId > 0 And ri.Author.AuthorId > 0 Then
                                    Dim oEmail As New Email
                                    oEmail.SendEmail(fi.ModApproveTemplateId, PortalId, ForumModuleId, ForumTabId, tmpForumId, tmpTopicId, tmpReplyId, String.Empty, ri.Author)
                                End If

                                Subscriptions.SendSubscriptions(PortalId, ForumModuleId, ForumTabId, tmpForumId, tmpTopicId, tmpReplyId, ri.Content.AuthorId)

                                Try
                                    Dim ctlUtils As New ControlUtils
                                    Dim fullURL As String = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, fi.ForumGroup.PrefixURL, fi.PrefixURL, fi.ForumGroupId, fi.ForumID, TopicId, ti.TopicUrl, -1, -1, String.Empty, 1, fi.SocialGroupId)
                                    If fullURL.Contains("~/") Or Not Request.QueryString("asg") Is Nothing Then
                                        fullURL = Utilities.NavigateUrl(ForumTabId, "", New String() {ParamKeys.TopicId & "=" & TopicId, ParamKeys.ContentJumpId & "=" & tmpReplyId})
                                    End If
                                    Dim amas As New Social
                                    If Request.QueryString("asg") Is Nothing And Not String.IsNullOrEmpty(MainSettings.ActiveSocialTopicsKey) And fi.ActiveSocialEnabled And Not fi.ActiveSocialTopicsOnly Then
                                        amas.AddReplyToJournal(PortalId, ForumModuleId, ForumId, ri.TopicId, ri.ReplyId, ri.Author.AuthorId, fullURL, ri.Content.Subject, String.Empty, sBody, fi.ActiveSocialSecurityOption, fi.Security.Read, fi.SocialGroupId)
                                    Else
                                        amas.AddForumItemToJournal(PortalId, ForumModuleId, ri.Author.AuthorId, "forumreply", fullURL, sSubject, sBody)
                                    End If
                                Catch ex As Exception
                                    DotNetNuke.Services.Exceptions.LogException(ex)
                                End Try

                            End If

                        End If


                End Select
                Dim cachekey As String = String.Format("AF-FV-{0}-{1}", PortalId, ModuleId)
                DataCache.CacheClearPrefix(cachekey)
            End If
            BuildModList()
            litTopics.RenderControl(e.Output)
        End Sub
#End Region
#Region "Private Members"
        Private Sub BuildModList()
            Dim sb As New Text.StringBuilder

            Dim ds As DataSet = DataProvider.Instance.Mod_Pending(PortalId, ModuleId, ForumId, UserId)
            Dim dtContent As DataTable = ds.Tables(0)
            Dim dtAttach As DataTable = ds.Tables(1)
            Dim dr As DataRow
            Dim tmpForum As String = String.Empty
            
            sb.Append("<div id=""afgrid"" style=""position:relative;""><table width=""100%"" cellpadding=""0"" cellspacing=""0"">")
            For Each dr In dtContent.Rows
                Dim forumKey As String = dr("ForumId").ToString & dr("ForumName").ToString
                If forumKey <> tmpForum Then
                    If ForumId = -1 Then
                        SetPermissions(CInt(dr("ForumId")))
                    End If
                    If bCanMod Then
                        If Not tmpForum = String.Empty Then
                            sb.Append("</td></tr>")
                        End If
                        Dim pendingCount As Integer = 0
                        dtContent.DefaultView.RowFilter = "ForumId = " & CInt(dr("ForumId"))
                        pendingCount = dtContent.DefaultView.ToTable.Rows.Count
                        dtContent.DefaultView.RowFilter = ""
                        sb.Append("<tr><td class=""afgrouprow"" style=""padding-left:10px;"">" & dr("GroupName").ToString & " > " & dr("ForumName").ToString & " [RESX:Pending]: (" & pendingCount & ")</td><td class=""afgrouprow"" align=""right"" style=""padding-right:5px;"">")
                        If ForumId = -1 Then
                            sb.Append("<img align=""absmiddle"" class=""afarrow"" id=""imgSection" & dr("ForumId").ToString & """ onclick=""aftoggleSection(" & dr("ForumId").ToString & ");"" src=""" & ImagePath & "/arrows_down.png"" /></td></tr>")
                            sb.Append("<tr id=""section" & dr("ForumId").ToString & """ style=""display:none;""><td colspan=""2"">")
                        Else
                            sb.Append("<img align=""absmiddle"" class=""afarrow"" id=""imgSection" & dr("ForumId").ToString & """ onclick=""aftoggleSection(" & dr("ForumId").ToString & ");"" src=""" & ImagePath & "/arrows_up.png"" /></td></tr>")
                            sb.Append("<tr id=""section" & dr("ForumId").ToString & """><td colspan=""2"">")
                        End If
                    End If
                    tmpForum = forumKey
                End If
                If bCanMod Then
                    sb.Append("<div class=""afmodrow"">")
                    sb.Append("<table width=""99%"">")
                    sb.Append("<tr><td style=""white-space:nowrap;"">" & GetDate(CDate(dr("DateCreated"))) & "</td>")
                    sb.Append("<td align=""right"">")
                    If bModApprove Then
                        sb.Append("<span class=""afminibtn"" onclick=""afmodApprove(" & dr("ForumId").ToString & "," & dr("TopicId").ToString & "," & dr("ReplyId").ToString & ");"" onmouseover=""this.className='afminibtn_over';"" onmouseout=""this.className='afminibtn';"">[RESX:Approve]</span>")
                    End If
                    'If bModApprove And bModMove And CInt(dr("ReplyId")) = 0 Then
                    '    sb.Append("<span class=""afminibtn"" onmouseover=""this.className='afminibtn_over';"" onmouseout=""this.className='afminibtn';"">[RESX:MoveApprove]</span>")
                    'End If
                    If bModApprove Or bModEdit Then
                        sb.Append("<span class=""afminibtn"" onclick=""javascript:if(confirm('[RESX:Confirm:Reject]')){afmodReject(" & dr("ForumId").ToString & "," & dr("TopicId").ToString & "," & dr("ReplyId").ToString & "," & dr("AuthorId").ToString & ");};"" onmouseover=""this.className='afminibtn_over';"" onmouseout=""this.className='afminibtn';"">[RESX:Reject]</span>")
                    End If
                    If bModDelete Then
                        sb.Append("<span class=""afminibtn"" onclick=""javascript:if(confirm('[RESX:Confirm:Delete]')){afmodDelete(" & dr("ForumId").ToString & "," & dr("TopicId").ToString & "," & dr("ReplyId").ToString & ");};"" onmouseover=""this.className='afminibtn_over';"" onmouseout=""this.className='afminibtn';"">[RESX:Delete]</span>")
                    End If
                    If bModEdit Then
                        sb.Append("<span class=""afminibtn"" onclick=""afmodEdit('" & TopicEditUrl(CInt(dr("ForumId")), CInt(dr("TopicId")), CInt(dr("ReplyId"))) & "');"" onmouseover=""this.className='afminibtn_over';"" onmouseout=""this.className='afminibtn';"">[RESX:Edit]</span>")
                    End If


                    sb.Append("</td></tr>")
                    sb.Append("<tr><td style=""width:90px"" valign=""top"">" & dr("AuthorName").ToString & "</td>")
                    sb.Append("<td><div class=""afrowsub"">[RESX:Subject]: " & dr("Subject").ToString & "</div><div class=""afrowbod"">" & dr("Body").ToString & "</div>")
                    sb.Append(GetAttachments(CInt(dr("ContentId")), True, PortalId, ModuleId, dtAttach) & "</td></tr>")
                    sb.Append("</table></div>")
                End If

            Next
            sb.Append("</table></div>")

            litTopics.Text = Utilities.LocalizeControl(sb.ToString)
        End Sub
        Private Function TopicEditUrl(ByVal ForumId As Integer, ByVal TopicId As Integer, ByVal ReplyId As Integer) As String
            If ReplyId = 0 Then
                Return NavigateUrl(TabId, "", New String() {ParamKeys.ViewType & "=post", "action=te", ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId})
            Else
                Return NavigateUrl(TabId, "", New String() {ParamKeys.ViewType & "=post", "action=re", ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId, "postid=" & ReplyId})
            End If
        End Function
        Private Sub SetPermissions(ByVal fId As Integer)
            Dim fc As New ForumController
            Dim f As Forum = fc.GetForum(PortalId, ModuleId, fId)
            bModDelete = False
            bModApprove = False
            bModEdit = False
            bModMove = False
            bCanMod = False
            If Not f Is Nothing Then
                bModDelete = Permissions.HasPerm(f.Security.ModDelete, ForumUser.UserRoles)
                bModApprove = Permissions.HasPerm(f.Security.ModApprove, ForumUser.UserRoles)
                bModMove = Permissions.HasPerm(f.Security.ModMove, ForumUser.UserRoles)
                bModEdit = Permissions.HasPerm(f.Security.ModEdit, ForumUser.UserRoles)
                If bModDelete Or bModApprove Or bModMove Or bModEdit Then
                    bCanMod = True
                End If

            End If

        End Sub
        Private Function GetAttachments(ByVal ContentId As Integer, ByVal AllowAttach As Boolean, ByVal PortalID As Integer, ByVal ModuleID As Integer, ByVal dtAttach As DataTable) As String
            Dim strHost As String = DotNetNuke.Common.AddHTTP(DotNetNuke.Common.GetDomainName(Request)) & "/"
            If Request.IsSecureConnection Then
                strHost = Replace(strHost, "http://", "https://")
            End If
            'TODO: Add option for folder storage
            Dim sb As New Text.StringBuilder
            If AllowAttach = True Then
                Dim vpath As String
                vpath = PortalSettings.HomeDirectory & "activeforums_Attach/"
                Dim fpath As String
                fpath = Server.MapPath(PortalSettings.HomeDirectory & "activeforums_Attach/")
                Dim dr As DataRow = Nothing
                dtAttach.DefaultView.RowFilter = "ContentId = " & ContentId
                For Each dr In dtAttach.DefaultView.ToTable.Rows
                    sb.Append("<br />")
                    Dim tmpPath As String
                    Dim attachId As Integer = CInt(dr("AttachId"))
                    Dim Filename As String = dr("Filename").ToString
                    Dim contentType As String = dr("ContentType").ToString
                    If dr.IsNull("FileData") Then
                        tmpPath = fpath & dr("Filename").ToString
                        If Not System.IO.File.Exists(tmpPath) Then
                            tmpPath = tmpPath.Replace("activeforums_Attach", "ntforums_attach")
                        End If
                        Dim strExt As String = System.IO.Path.GetExtension(tmpPath)
                        Select Case strExt.ToUpper
                            Case ".JPG", ".JPEG", ".GIF", ".PNG"
                                sb.Append("<br><span class=""afimage""><img src=""" & vpath & Filename & """ border=""0"" align=""center"" /></span><br /><br />")
                            Case Else
                                sb.Append("<a href=""" & vpath & Filename & """ target=""_blank""><img src=""" & strHost & "DesktopModules/ActiveForums/images/attach.gif"" border=""0"" align=""absmiddle"">Attachment: " & Filename & "</a><br>")
                        End Select
                    Else
                        Select Case contentType.ToLower
                            Case "image/jpeg", "image/pjpeg", "image/gif", "image/png"
                                sb.Append("<br /><span class=""afimage""><img src=""" & strHost & "DesktopModules/ActiveForums/viewer.aspx?portalid=" & PortalID & "&moduleid=" & ModuleID & "&attachid=" & attachId & """ border=0 align=center></span><br><br>")
                            Case Else
                                sb.Append("<span class=""afattachlink""><a href=""" & strHost & "DesktopModules/ActiveForums/viewer.aspx?portalid=" & PortalID & "&moduleid=" & ModuleID & "&attachid=" & attachId & """ target=""_blank""><img src=""" & strHost & "DesktopModules/ActiveForums/images/attach.gif"" border=""0"" align=""absmiddle"">Attachment: " & Filename & "</a></span><br />")
                        End Select
                    End If
                Next
                sb.Append("<br />")

                Return sb.ToString
            Else
                Return String.Empty
            End If
        End Function
#End Region


    End Class
End Namespace
